package cn.edu.jxau.test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

public class Main {

	public static void main(String[] args) throws IOException {

		Main m = new Main();
		System.out.println(m.replaceSpace("Hello  World", 12));
	}

	public String replaceSpace(String iniString, int length) {

		// 1.参数校验 //
		Objects.requireNonNull(iniString, "参数iniString不能为null");
		if (length < 0) {
			throw new IllegalArgumentException("参数length不能为负数");
		}
		// 2.计算空格数 //
		int spaceCount = 0;
		for (int i = 0, end = iniString.length(); i < end; i++) {
			if (iniString.charAt(i) == ' ') {
				spaceCount++;
			}
		}
		// 3.replace space //
		int newLen = iniString.length() + spaceCount * 2;
		char[] charArr = new char[newLen];
		int cur = newLen - 1;
		for (int i = iniString.length() - 1; i >= 0; i--) {
			char ch = iniString.charAt(i);
			if (ch == ' ') {
				charArr[cur--] = '0';
				charArr[cur--] = '2';
				charArr[cur--] = '%';
			} else {
				charArr[cur--] = ch;
			}
		}
		return new String(charArr);
	}
}